package Dao.impl;

import Dao.ProDao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import pojo.Pro;
import utils.DruidUtils;

import java.sql.SQLException;
import java.util.List;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.8.27 下午 16:43
 */
public class ProDaoimpl implements ProDao {

    @Override
    public List<Pro> selectProductAll() {
        try {
            //创建执行对象
            QueryRunner qr = new QueryRunner(DruidUtils.getDataSourse());
            //sql
            String sql = "select * from   Pro";
            List<Pro> list = qr.query(sql, new BeanListHandler<Pro>(Pro.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int delete(int id) {
        try {
            QueryRunner qr = new QueryRunner(DruidUtils.getDataSourse());
            String sql = "delete from Pro where id = ?";
            qr.update(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int add(Pro pro) {
        try {
            QueryRunner qr = new QueryRunner(DruidUtils.getDataSourse());
            String sql = "insert into Pro (id,pname,pprice,pdesc) values(?,?,?,?)";
            qr.update(sql, pro.getId(), pro.getPname(), pro.getPprice(), pro.getPdesc());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delete(String pname) {
        try {
            QueryRunner qr = new QueryRunner(DruidUtils.getDataSourse());
            String sql = "delete from Pro where pname = ?";
            return qr.update(sql, pname);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(Pro pro) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSourse());
        try {
            String sql2 = "update Pro set pname = ? where id = ?";
            queryRunner.update(sql2,pro.getPname(),pro.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            String sql3 = "update Pro set pprice = ? where id = ?";
            queryRunner.update(sql3,pro.getPprice(),pro.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            String sql4 = "update Pro set pdesc = ? where id = ?";
            queryRunner.update(sql4,pro.getPdesc(),pro.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
